package org.dromara.bean.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.dromara.bean.config.AppTypeConfig;
import org.dromara.bean.config.WxConfig;
import org.dromara.bean.domain.HisMember;
import org.dromara.bean.mapper.HisMemberMapper;

import org.dromara.bean.service.IBaseWechatService;
import org.dromara.bean.util.HttpUtil;
import org.dromara.common.core.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;


/**
 * 小程序-公众号的封装
 */
@Slf4j
@Service
public class BaseWechatServiceImpl extends ServiceImpl<HisMemberMapper, HisMember> implements IBaseWechatService {
//    @Autowired
//    private RedisUtil redisUtil;
    @Autowired
    private DictService baseDictService;
    @Autowired
    private AppTypeConfig appTypeConfig;

    public static JSONObject getSessionKeyOrOpenId(String code, String appId, String appSecret) {
        //微信端登录code
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> requestUrlParam = new HashMap<String, String>();
        requestUrlParam.put("appid", appId);//小程序appId
        requestUrlParam.put("secret", appSecret);
        requestUrlParam.put("js_code", code);//小程序端返回的code
        requestUrlParam.put("grant_type", "authorization_code");//默认参数
        log.warn("请求地址：【{}】，请求参数：【{}】", requestUrl, JSONObject.toJSONString(requestUrlParam));
        //发送post请求读取调用微信接口获取openid用户唯一标识
        String response = HttpUtil.doGet(requestUrl, requestUrlParam);
        log.warn("回文：【{}】", response);
        JSONObject jsonObject = JSON.parseObject(response);
        return jsonObject;
    }


//    @Override
//    public String getUrlLink(String type, String userType, String path, String query) throws Exception {
//        String accessToken = getAccessToken(type, userType);
//        String urlLink = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + accessToken;
//        RestTemplate restTemplate = new RestTemplate();
//        JSONObject body = new JSONObject();
//        body.put("path", path);
//        body.put("query", query);
//        body.put("env_version", "release");
//        body.put("is_expire", true);
//        body.put("expire_type", 1);
//        body.put("expire_interval", 1);
//        String response = restTemplate.postForObject(urlLink, body.toJSONString(), String.class);
//        log.warn("获取UrlLink回文:【{}】,", response);
//        JSONObject responseObj = JSONObject.parseObject(response);
//        if (!responseObj.getInteger("errcode").equals(0)) {
//            throw new Exception("获取失败！");
//        }
//        return responseObj.getString("url_link");
//    }

//    /**
//     * 微信分享获取签名的accessToken
//     *
//     * @param type
//     * @return
//     */
//    @Override
//    public String getAccessToken(String type, String userType) {
//        String accessToken = "";
//        //获取access_token填写client_credential
//        String grant_type = "client_credential";
//        String AppId = "";
//        String secret = "";//第三方用户唯一凭证密钥，即appsecret
//        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?";
//        UserTypeConfig userTypeConfig = baseDictService.getUserType();
//        WxConfig appConfig = baseDictService.getDictToObj("wx_config", new WxConfig());
//        if ("mini".equals(type)) {
//            String accessTokenMini = "";
//            boolean hasAccessToken = redisUtil.hasKey("accessTokenMini:" + userType);
//            if (hasAccessToken) {
//                log.warn("accessTokenMini:{} 缓存token", userType);
//                return (String) redisUtil.get("accessTokenMini:" + userType);
//            }
//            if (userType.equals(userTypeConfig.getUser_type_patient())) {
//                AppId = appConfig.getMemberMiniAppId();
//                secret = appConfig.getMemberMiniAppSecret();
//            }
//            if (userType.equals(userTypeConfig.getUser_type_doctor())) {
//                AppId = appConfig.getDoctorMiniAppId();
//                secret = appConfig.getDoctorMiniAppSecret();
//            }
//            if (userType.equals(userTypeConfig.getUser_type_phr())) {
//                AppId = appConfig.getPhcMiniAppId();
//                secret = appConfig.getPhcMiniAppSecret();
//            }
//            RestTemplate restTemplate = new RestTemplate();
//            String url = accessTokenUrl + "grant_type=" + grant_type + "&" +
//                    "appid=" + AppId + "&secret=" + secret;
//            String json = restTemplate.getForObject(url, String.class);
//            JSONObject myJson = JSONObject.parseObject(json);
//            if (myJson.containsKey("access_token")) {
//                accessTokenMini = myJson.get("access_token").toString();
//                redisUtil.set("accessTokenMini：" + userType, accessTokenMini);
//                redisUtil.expire("accessTokenMini", 7200);
//            }
//            log.warn("access_token获取请求：-------------------" + JSONObject.toJSONString(myJson));
//            accessToken = accessTokenMini;
//        }
//        //获取微信公众号access_token
//        if ("wechat".equals(type)) {
//            AppId = appConfig.getWechatAppId();
//            secret = appConfig.getWechatAppSecret();
//            String accessTokenWechat = "";
//            boolean hasAccessToken = redisUtil.hasKey("accessTokenWechat");
//            if (hasAccessToken) {
//                return (String) redisUtil.get("accessTokenWechat");
//            }
//            RestTemplate restTemplate = new RestTemplate();
//            String url = accessTokenUrl + "grant_type=" + grant_type + "&" +
//                    "appid=" + AppId + "&secret=" + secret;
//            String json = restTemplate.getForObject(url, String.class);
//            JSONObject myJson = JSONObject.parseObject(json);
//            log.warn("access_token获取请求：-------------------" + JSONObject.toJSONString(myJson));
//            if (myJson.containsKey("access_token")) {
//                accessTokenWechat = myJson.getString("access_token");
//                redisUtil.set("accessTokenWechat", accessTokenWechat);
//                redisUtil.expire("accessTokenWechat", 7200);
//            }
//            accessToken = accessTokenWechat;
//        }
//        return accessToken;
//    }

//    /**
//     * 获取accessToken
//     *
//     * @param appWechatLoginModel
//     * @param appType
//     * @param userType
//     * @return
//     */
//    @Override
//    public JSONObject getAccessTokenWechatUserInfo(WechatLoginModel appWechatLoginModel, String appType, String userType) {
//        String code = appWechatLoginModel.getCode();
//        JSONObject appInfoByType = getAppInfoByType(appType);
//
//        //通过小程序
//        if (appTypeConfig.getTecMiniApp().equals(appType) || appTypeConfig.getDoctorMiniApp().equals(appType)
//                || appTypeConfig.getPatientMiniApp().equals(appType) || appTypeConfig.getPhcMiniApp().equals(appType)
//                || appTypeConfig.getTecMiniApp().equals(appType)) {
//            return this.getOpenIdByMiniAPP(appInfoByType.getString("appId"), appInfoByType.getString("appSecret"), code);
//        }
//        //通过微信公众号或者开放平台
//        if (appTypeConfig.getNurseWechatApp().equals(appType) || appTypeConfig.getDoctorWechatApp().equals(appType)
//                || appTypeConfig.getPatientWechatApp().equals(appType) || appTypeConfig.getPhcWechatApp().equals(appType)
//                || appTypeConfig.getTecWechatApp().equals(appType)) {
//            return this.getOpenIdByWechatAPP(appInfoByType.getString("appId"), appInfoByType.getString("appSecret"), code);
//        }
//        return null;
//    }

    /**
     * 这是通过小程序获取openid 统一方法
     *
     * @param appId
     * @param appSecret
     * @param code
     * @return
     */
    public JSONObject getOpenIdByMiniAPP(String appId, String appSecret, String code) {
        JSONObject sessionKeyOrOpenId = getSessionKeyOrOpenId(code, appId, appSecret);
        log.warn("sessionKeyOrOpenId------------------------" + JSONObject.toJSONString(sessionKeyOrOpenId));
        return sessionKeyOrOpenId;
    }

    /**
     * 这是通过公众号获取openid 统一方法
     *
     * @param appId
     * @param appSecret
     * @param code
     * @return
     */
    public JSONObject getOpenIdByWechatAPP(String appId, String appSecret, String code) {
        String openidUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?";
        StringBuilder url = new StringBuilder();
        url.append(openidUrl);
        url.append("appid=");
        url.append(appId.trim());
        url.append("&secret=");
        url.append(appSecret.trim());
        url.append("&code=");
        url.append(code);
        url.append("&grant_type=authorization_code");
        RestTemplate restTemplate = new RestTemplate();
        String json = restTemplate.getForObject(url.toString(), String.class);
        JSONObject jsonObject = JSONObject.parseObject(json);
        log.warn("accessTokenWechatUserInfo------------------------" + JSONObject.toJSONString(jsonObject));

        return jsonObject;
    }

    //获取ticket
//    @Override
//    public String getTicket(String accessToken) {
//        String ticket = null;
//        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi";// 这个url链接和参数不能变
//        RestTemplate restTemplate = new RestTemplate();
//        String json = restTemplate.getForObject(url, String.class);
//        JSONObject myJson = JSONObject.parseObject(json);
//        log.warn("ticket获取请求：-------------------" + JSONObject.toJSONString(myJson));
//        if (myJson.containsKey("ticket")) {
//            ticket = myJson.get("ticket").toString();
//        }
//        return ticket;
//    }

//    @Override
//    public WeiXinModel getWinXinEntity(String url, String ticket) {
//        WeiXinModel wx = new WeiXinModel();
//        Map<String, String> ret = WeiXinSign.sign(ticket, url);
//        wx.setTicket(ret.get("jsapi_ticket"));
//        wx.setSignature(ret.get("signature"));
//        wx.setNoncestr(ret.get("nonceStr"));
//        wx.setTimestamp(ret.get("timestamp"));
//        return wx;
//    }

//    @Override
//    public BaseWechatUserModel getUserInfo(String openid, String accessToken) {
//        BaseWechatUserModel baseWechatUserModel = new BaseWechatUserModel();
//        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openid + "&lang=zh_CN";// 这个url链接和参数不能变
//        RestTemplate restTemplate = new RestTemplate();
//        String json = restTemplate.getForObject(url, String.class);
//        // 编码后的json
//        try {
//            json = new String(json.getBytes("ISO-8859-1"), "UTF-8");
//            JSONObject userInfoJO = JSONObject.parseObject(json);
//            baseWechatUserModel.setCity(userInfoJO.getString("city"));
//            baseWechatUserModel.setCountry(userInfoJO.getString("country"));
//            baseWechatUserModel.setOpenId(userInfoJO.getString("openid"));
//            baseWechatUserModel.setHeadImgUrl(userInfoJO.getString("headimgurl"));
//            baseWechatUserModel.setNickname(userInfoJO.getString("nickname"));
//            baseWechatUserModel.setProvince(userInfoJO.getString("province"));
//            baseWechatUserModel.setGender(userInfoJO.getString("sex"));
//            log.warn("微信getUserInfo请求：-------------------" + JSONObject.toJSONString(userInfoJO));
//        } catch (Exception e) {
//            log.warn("获取个人信息失败。。。。。。");
//        }
//        return baseWechatUserModel;
//    }

    /**
     * 根据当前的app类型获取该app的基本信息
     *
     * @param appType
     * @return
     */
    @Override
    public JSONObject getAppInfoByType(String appType) {
        JSONObject appTypeList = new JSONObject();
        String appId = "";
        String appSecret = "";
        WxConfig appConfig = baseDictService.getDictToObj("wx_config", new WxConfig());

        //患者小程序
        appId = appConfig.getAppId();
        appSecret = appConfig.getAppSecret();


        appTypeList.put("appId", appId);
        appTypeList.put("appSecret", appSecret);
        return appTypeList;
    }


}
